/*
 * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package org.jetbrains.kotlin.generators.frontend;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.generators.util.GeneratorsFileUtil;
import org.jetbrains.kotlin.lexer.KtKeywordToken;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.utils.Printer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GenerateKeywordStrings {
    public static final File DEST_FILE = new File("core/compiler.common/src/org/jetbrains/kotlin/renderer/KeywordStringsGenerated.java");

    @NotNull
    public static String generate() throws IOException {
        StringBuilder sb = new StringBuilder();
        Printer p = new Printer(sb);

        p.println(FileUtil.loadFile(new File("license/COPYRIGHT_HEADER.txt")));
        p.println();
        p.println("package org.jetbrains.kotlin.renderer;");
        p.println();
        p.println("import java.util.Arrays;");
        p.println("import java.util.Set;");
        p.println("import java.util.HashSet;");
        p.println();
        p.println("/** This class is generated by {@link \"org.jetbrains.kotlin.generators.frontend.GenerateKeywordStrings\"}. DO NOT MODIFY MANUALLY */");
        p.println("public class KeywordStringsGenerated {");
        p.pushIndent();
        p.println("private KeywordStringsGenerated() {}");
        p.println();
        p.println("public static final Set<String> KEYWORDS = new HashSet<String>(Arrays.asList(");
        p.pushIndent();

        List<String> strings = new ArrayList<>();
        for (IElementType type : KtTokens.KEYWORDS.getTypes()) {
            assert type instanceof KtKeywordToken : "Not a keyword in KtTokens.KEYWORDS: " + type;
            KtKeywordToken keyword = (KtKeywordToken) type;
            assert !keyword.isSoft() : "Soft keyword in KtTokens.KEYWORDS: " + keyword.getValue();
            if (keyword != KtTokens.AS_SAFE && keyword != KtTokens.NOT_IN && keyword != KtTokens.NOT_IS) {
                strings.add(keyword.getValue());
            }
        }

        for (Iterator<String> iterator = strings.iterator(); iterator.hasNext(); ) {
            String string = iterator.next();
            p.println("\"" + string + "\"" + (iterator.hasNext() ? "," : ""));
        }

        p.popIndent();
        p.println("));");
        p.popIndent();
        p.println("}");

        return sb.toString();
    }

    public static void main(String[] args) throws IOException {
        GeneratorsFileUtil.writeFileIfContentChanged(DEST_FILE, generate());
    }
}
